package net.hky365.lowcode.magic.utils;

import org.apache.ibatis.reflection.ArrayUtil;
import org.slf4j.Logger;

import java.sql.Array;
import java.sql.SQLException;
import java.util.Arrays;

public class MagicJdbcLogger {
    protected final Logger statementLog;
    protected int queryStack = 1;

    /*
     * Default constructor
     */
    public MagicJdbcLogger(Logger log) {
        this.statementLog = log;
    }

    public static String objectValueString(Object value) {
        if (value instanceof Array) {
            try {
                return ArrayUtil.toString(((Array) value).getArray());
            } catch (SQLException e) {
                // Intentialy fall through to return value.toString()
            }
        }
        return value.toString();
    }

    public boolean isDebugEnabled() {
        return statementLog.isDebugEnabled();
    }

    public void debug(boolean input, String format, Object... arguments) {
        if (isDebugEnabled()) {
            statementLog.debug(prefix(input) + format, arguments);
        }
    }

    public boolean isInfoEnabled() {
        return statementLog.isInfoEnabled();
    }

    public void info(boolean input, String format, Object... arguments) {
        if (isInfoEnabled()) {
            statementLog.info(prefix(input) + format, arguments);
        }
    }

    public boolean isTraceEnabled() {
        return statementLog.isTraceEnabled();
    }

    public void trace(boolean input, String format, Object... arguments) {
        if (isTraceEnabled()) {
            statementLog.trace(prefix(input) + format, arguments);
        }
    }

    public void error(boolean input, String format, Object... arguments) {
        statementLog.error(prefix(input) + format, arguments);
    }

    private String prefix(boolean isInput) {
        char[] buffer = new char[queryStack * 2 + 2];
        Arrays.fill(buffer, '=');
        buffer[queryStack * 2 + 1] = ' ';
        if (isInput) {
            buffer[queryStack * 2] = '>';
        } else {
            buffer[0] = '<';
        }
        return new String(buffer);
    }
}
